package chat

import (
	"WeiPublishChat/codes/config"
	checksignature "WeiPublishChat/codes/utils/CheckSignature"
	"encoding/xml"
	"fmt"
	"log"
	"time"

	"github.com/gin-gonic/gin"
)

// WXCheckSignature 微信接入校验
func WXCheckSignature(c *gin.Context) {
	signature := c.Query("signature")
	timestamp := c.Query("timestamp")
	nonce := c.Query("nonce")
	echostr := c.Query("echostr")
	ok := checksignature.CheckSignature(signature, timestamp, nonce, config.Token)
	if !ok {
		log.Println("微信公众号接入校验失败!")
		return
	}

	log.Println("微信公众号接入校验成功!")
	_, _ = c.Writer.WriteString(echostr)
}

func WXInterflow(c *gin.Context) {
	var textMsg config.WXTextMsg
	//微信消息接收
	WXMsgReceive(c, &textMsg)
	//消息分词
	
	// 对接收的消息进行被动回复
	WXMsgReply(c, textMsg.ToUserName, textMsg.FromUserName, textMsg.Content)
}

// WXMsgReceive 微信消息接收
func WXMsgReceive(c *gin.Context, textMsg *config.WXTextMsg) {
	err := c.ShouldBindXML(&textMsg)
	if err != nil {
		log.Printf("[消息接收] - XML数据包解析失败: %v\n", err)
		return
	}

	log.Printf("[消息接收] - 收到消息, 消息类型为: %s, 消息内容为: %s\n", textMsg.MsgType, textMsg.Content)
}

// WXMsgReply 微信消息回复
func WXMsgReply(c *gin.Context, fromUser, toUser, content string) {
	repTextMsg := config.WXRepTextMsg{
		ToUserName:   toUser,
		FromUserName: fromUser,
		CreateTime:   time.Now().Unix(),
		MsgType:      "text",
		Content:      fmt.Sprintf("[接收消息：%s]--在%s", content, time.Now().Format("2006-01-02 15:04:05")),
	}

	msg, err := xml.Marshal(&repTextMsg)
	if err != nil {
		log.Printf("[消息回复] - 将对象进行XML编码出错: %v\n", err)
		return
	}
	_, _ = c.Writer.Write(msg)
}
